﻿using MediatR;
using Medical.Api.Write.Application.Command.RecyclingCleaning;
using Medical.Domain.RecoveryCleaning;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Medical.Domain.Enum;

namespace Medical.Api.Write.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 撤销清洗状态命令处理
    /// </summary>
    public class CancelCleaningStateCommandHandlter : IRequestHandler<CancelCleaningStateCommand, ApiResult<int>>
    {
        /// <summary>
        /// 清洗仓储
        /// </summary>
        private readonly IBaseRepository<CleaningRegistration> cleaningRegistrationRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="cleaningRegistrationRepository">清洗仓储</param>
        public CancelCleaningStateCommandHandlter(IBaseRepository<CleaningRegistration> cleaningRegistrationRepository)
        {

            this.cleaningRegistrationRepository = cleaningRegistrationRepository;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>

        public async Task<ApiResult<int>> Handle(CancelCleaningStateCommand request, CancellationToken cancellationToken)
        {
            // 根据ID获取清洗登记信息
            var cleaningRegistration = cleaningRegistrationRepository.GetAll().FirstOrDefault(x=>x.Id== request.Id&&!x.IsDeleted);
            
            // 如果未找到记录，返回错误
            if (cleaningRegistration == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "未找到对应的清洗记录"
                };
            }

            // 检查是否为已清洗状态，如果是则修改为已回收
            if (cleaningRegistration.CleaningState == RecoveryStatusEnum.已完成)
            {
                cleaningRegistration.CleaningState = RecoveryStatusEnum.待清洗;
                
                // 保存更改
                cleaningRegistrationRepository.Update(cleaningRegistration);
                
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = 1,
                    Msg = "撤销成功"
                };
            }
            else
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "当前清洗状态不是已清洗，无法撤销"
                };
            }
        }
    }
}
